<!-- <template>
  <div class="main">
    <div class="chat-left">
      <p class="chat-left_title">
        任务类型：<span class="parameter" style="display: inline-block"
          >{{ this.taskType }}迁移(
            <span class="a" @click="previewCode = true">{{ sinkObjectName }}</span>
          )</span
        >
      </p>
      <p class="chat-left_title" v-if="databaseInfo">
        源端：<span class="parameter a" @click="()=>handleDatabaseInfo('source')">{{ databaseInfo.sourceName }}</span>
      </p>
      <p class="chat-left_title" v-if="databaseInfo">
        目标端：<span class="parameter a" @click="()=>handleDatabaseInfo('sink')">{{ databaseInfo.sinkName }}</span>
      </p>
      <p class="chat-left_title">
        AI列表
        <el-select v-model="aiModel" style="margin: 8px 0;display:block;">
          <el-option
            v-for="item in aiModelList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </p>
      <p class="chat-left_title" style="height:60%;">历史提问
        <ul>
          
          <li @click="previewMessage(i)" v-for="(f,i) in historyQuestioning" :key="f.message">
            <el-tooltip popper-class="ai-history-tooltip" effect="dark" :content="f.title" placement="top-start">
              <p>{{ f.title }}</p> 
            </el-tooltip>
            <span>#{{ i + 1 }}</span>
          </li>
        </ul>
      </p>
    </div>
    <div class="chat-right">
      <Chat :taskType="taskType" @getHistory-event="getHistory" :aiModelValue="aiModel" :databaseInfo="databaseInfo" :executeSqlData="executeSqlData"/>
    </div>

    <el-dialog v-if="NextdataDialog" title="数据源信息" width="800px" :visible.sync="NextdataDialog">
      <databaseView :form="databaseInfoValue" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="testConnect">测试连接</el-button>
        <el-button type="primary" @click="NextdataDialog = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="数据源信息" width="800px" :visible.sync="previewCode">
      <div>
        <editor
          @init="editorInit"
          ref="aceEditor"
          v-model="ddl"
          width="100%"
          :height="400"
          lang="sql"
          theme="dracula"
          :options="{
            enableBasicAutocompletion: true,
            enableSnippets: true,
            enableLiveAutocompletion: true,
            showPrintMargin: false, 
            fontSize: 16,
          }"
        ></editor>
        <el-button
        style="margin-top: 20px"
        type="primary"
        icon="el-icon-document-copy"
        size="small"
        @click="copyDdl()"
        >复制</el-button
      >
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="previewCode = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-if="previewMessageValue" :title="previewMessageValue.title.length > 15 ? `${previewMessageValue.title.slice(0,15)}...`:previewMessageValue.title" width="800px" :visible.sync="previewMessageVisible">
        <div style="max-height:500px;overflow-y:auto">
          <div style="text-align: right"><p class="message-content">{{ previewMessageValue.history.user }}</p></div>
          <Markdown
            ref="mark"
            :source="previewMessageValue.history.ai"
            :executeSqlData="executeSqlData"
        />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="previewMessageVisible = false">确 定</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAiList } from "@/api/console/belfAi";
import Chat from './components/chat.vue'
import databaseView from './components/databaseView.vue'
import { getDataTaskconf } from "@/api/console/dataTaskconf.js";
import Markdown from "@/components/marckdown";
import {
  getDatasourceInfo,
  databaseCheck,
} from "@/api/console/datasourceInfo";
export default {
  name: "migrationReportAi",
  components: {
    Chat,
    databaseView,
    editor: require("vue2-ace-editor") ,
    Markdown
  },
  dicts:['transfer_result_object_type'],
  data() {
    return {
      previewCode:false,
      aiModel: "Doubao-lite-32k",
      aiModelList: [],
      taskType:null,
      databaseInfo:null,
      NextdataDialog:false,
      databaseInfoValue:{},
      sinkObjectName:null,
      ddl:null,
      historyQuestioning:[],
      executeSqlData:null,
      previewMessageVisible:false,
      previewMessageValue:null,

    };
  },
  async mounted() {
    const { type , taskId,sinkObjectName,sinkDdl,sourceDdl } = JSON.parse(localStorage.getItem("migrationReportAi"));
    this.sinkObjectName = sinkObjectName;
    let res = await this.getDicts('transfer_result_object_type');
    this.taskType =  res.data.filter(f=>f.dictValue.includes(type))[0].dictLabel;
    res = await getDataTaskconf({
      id: taskId,
    })
    this.databaseInfo = res.data;
    if (sourceDdl && sourceDdl.length > 0) {
      this.ddl = sourceDdl;
      this.executeSqlData = {
        databaseName: this.databaseInfo.sourceName,
        datasourceId: this.databaseInfo.sourceId
      }
    }else{
      this.ddl = sinkDdl;
      this.executeSqlData = {
        databaseName: this.databaseInfo.sinkName,
        datasourceId: this.databaseInfo.sinkId
      }
    }
    res = await getAiList();
    Object.keys(this.sort(res)).forEach((f) => {
      this.aiModelList.push({
        label: `${res[f]}(${f})`,
        value: f,
      });
    });
  },
  methods:{
    previewMessage(i){
      this.previewMessageValue = this.historyQuestioning[i];
      this.previewMessageVisible = true;
    },
    sort(data){
      const sortedData = Object.entries(data).sort((a, b) => {
        const [keyA, valueA] = a;
        const [keyB, valueB] = b;
        return valueA.split('-')[0].localeCompare(valueB.split('-')[0]);
      });
      const result = Object.fromEntries(sortedData);
      return result;
    },
    copyDdl() {
      const dom = document.createElement("input");
      dom.value = this.ddl;
      document.body.appendChild(dom);
      dom.select();
      document.execCommand("copy");
      document.body.removeChild(dom);
      this.$message.success("复制成功");
    },
    editorInit() {
      // 初始化
      require("brace/ext/language_tools");
      require("brace/ext/beautify");
      require("brace/ext/error_marker");
      require("brace/ext/searchbox");
      require("brace/ext/split");
      require("brace/snippets/sql");
      require("brace/mode/sql");
      require("brace/theme/dracula");
    },
    getHistory(history){
      let arr =[];
      history.forEach((f,i)=>{
        // console.log();
        if (i % 2 != 0) {
          if (f.type == 'error'){
            return;
          }else{
            arr.unshift({
              title:history[i-1].message,
              history:{
                user:history[i-1].message,
                ai:f.message
              }
            })
          }
        }
      })
      // console.log(arr);
      this.historyQuestioning = arr;
    },
    handleDatabaseInfo(type){
      getDatasourceInfo({
        id: this.databaseInfo[`${type}Id`],
      }).then((response) => {
        this.databaseInfoValue = response.data;
        this.NextdataDialog  = true;
      })
    },
    async testConnect() {
      const {
        type,
        ip,
        port,
        uname,
        pwd,
        databaseName,
        version,
        encoding,
        useUnicode,
        connectTimeout,
        socketTimeout,
        driver,
        url,
      } = this.databaseInfoValue;
      const response = await databaseCheck({
        type,
        ip,
        port,
        uname,
        pwd,
        databaseName,
        version,
        encoding,
        useUnicode,
        connectTimeout,
        socketTimeout,
        driver,
        url,
      });
      if (response.data.code == 200) {
        this.$message({
          message: "连接成功",
          type: "success",
        });
        this.form.testStatus = 0;
      } else {
        this.form.testStatus = 1;
        this.$message.error("连接失败");
      }
      this.getList();
    },
  }
};
</script>

<style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  display: flex;
  background-color: rgb(243, 244, 246);
  min-width: 1080px;

  .chat-left {
    width: 280px;
    padding: 0.5rem;
    height: 100%;
    background-color: #fff;
    box-shadow: 10px 0 10px -5px rgba(192, 192, 192, 0.3);

    .parameter {
      color: #424242;
      font-weight: 500;
      font-size: 13px;
      margin: 8px 0;
    }

    .a{
      color: blue;
      cursor: pointer;
    }

    .chat-left_title {
      font-weight: 600;
      color: #000;
      margin:0 0 15px 0;
      font-size: 14px;
    }


    ul{
      list-style-type: none;
      padding: 0;
      margin: 0;
      width: 100%;

      li{
        font-weight: 500;
        font-size: 13px;
        width: 95%;
        background: rgb(243, 244, 246);
        padding: 5px;
        border-radius: 3px;
        color: #222;
        margin: 8px 0;
        cursor: pointer;
        display: flex;
        align-items: center;
       p{
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        width: 90%;
        margin: 0;
       }
      }
    }
  }

  .chat-right {
    width: calc(100% - 280px);
    height: 100%;
  }

  .message-content{
    text-align: left;
    word-break: break-word;
    white-space: pre-wrap;
    border-radius: 15px;
    padding: 5px 10px;
    font-size: 14px;
    display: inline-block;
    width: auto;
    color: #121512;
    background-color: rgb(245, 245, 245);
    margin: 0;
  }
}

</style>
<style>
.ai-history-tooltip{
  max-width: 500px !important;
}
</style> -->

<template>
  <div class="main">
    <div class="chat-left" :style="{ width: leftWidth }">
      <div class="contract">
        <p class="contract_title" v-if="leftWidth == '480px'">源端信息</p>
        <div
          class="svg_box"
          :style="{ transform: leftWidth == '480px' ? '' : 'rotate(180deg)' }"
          @click="handleChangeLeftWidth"
        >
          <svg
            width="20"
            height="20"
            viewBox="0 0 17 17"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <g opacity="0.6">
              <path
                d="M5.35156 8.5H15.3516"
                stroke="#333333"
                stroke-width="1.5"
                stroke-linecap="round"
                stroke-linejoin="round"
              ></path>
              <path
                d="M9.09347 13.1559L4.4375 8.49981L9.09347 3.84375"
                stroke="#333333"
                stroke-width="1.5"
                stroke-linecap="round"
                stroke-linejoin="round"
              ></path>
              <rect
                x="0.351562"
                y="2.5"
                width="1.5"
                height="12"
                rx="0.75"
                fill="#333333"
              ></rect>
            </g>
          </svg>
        </div>
      </div>
      <ul class="database_info" v-if="leftWidth == '480px'">
        <li>
          <span class="database_info-title">名称：</span
          ><span class="database_info-item">MySQL 5.7 关系型数据</span>
        </li>
        <li>
          <span class="database_info-title">ip：</span
          ><span class="database_info-item">39.105.183.163</span>
        </li>
        <li>
          <span class="database_info-title">端口：</span
          ><span class="database_info-item">5236</span>
        </li>
      </ul>
    </div>
    <div class="content">
      <Chat
        :taskType="taskType"
        @getHistory-event="getHistory"
        :aiModelValue="aiModel"
        :databaseInfo="databaseInfo"
        :executeSqlData="executeSqlData"
      />
    </div>
    <div class="chat-left boxShadow" :style="{ width: rightWidth }">
      <div class="contract">
        <div
          class="svg_box"
          :style="{ transform: rightWidth == '480px' ? 'rotate(180deg)' : '' }"
          @click="handleChangeRightWidth"
        >
          <svg
            width="20"
            height="20"
            viewBox="0 0 17 17"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <g opacity="0.6">
              <path
                d="M5.35156 8.5H15.3516"
                stroke="#333333"
                stroke-width="1.5"
                stroke-linecap="round"
                stroke-linejoin="round"
              ></path>
              <path
                d="M9.09347 13.1559L4.4375 8.49981L9.09347 3.84375"
                stroke="#333333"
                stroke-width="1.5"
                stroke-linecap="round"
                stroke-linejoin="round"
              ></path>
              <rect
                x="0.351562"
                y="2.5"
                width="1.5"
                height="12"
                rx="0.75"
                fill="#333333"
              ></rect>
            </g>
          </svg>
        </div>
        <p class="contract_title" v-if="rightWidth == '480px'">目标端信息</p>
      </div>
      <ul class="database_info" v-if="rightWidth == '480px'">
        <li>
          <span class="database_info-title">名称：</span
          ><span class="database_info-item">MySQL 5.7 关系型数据</span>
        </li>
        <li>
          <span class="database_info-title">ip：</span
          ><span class="database_info-item">39.105.183.163</span>
        </li>
        <li>
          <span class="database_info-title">端口：</span
          ><span class="database_info-item">5236</span>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Chat from "./components/chat.vue";
import { getAiList } from "@/api/console/belfAi";
import databaseView from "./components/databaseView.vue";
import { getDataTaskconf } from "@/api/console/dataTaskconf.js";
import Markdown from "@/components/marckdown";
import { getDatasourceInfo, databaseCheck } from "@/api/console/datasourceInfo";
export default {
  name: "migrationReportAi",
  components: {
    Chat,
    databaseView,
    editor: require("vue2-ace-editor"),
    Markdown,
  },
  dicts: ["transfer_result_object_type"],
  data() {
    return {
      leftWidth: "480px",
      rightWidth: "480px",
      previewCode: false,
      aiModel: "Doubao-lite-32k",
      aiModelList: [],
      taskType: null,
      databaseInfo: null,
      NextdataDialog: false,
      databaseInfoValue: {},
      sinkObjectName: null,
      ddl: null,
      historyQuestioning: [],
      executeSqlData: null,
      previewMessageVisible: false,
      previewMessageValue: null,
    };
  },
  async mounted() {
    const { type, taskId, sinkObjectName, sinkDdl, sourceDdl } = JSON.parse(
      localStorage.getItem("migrationReportAi")
    );
    this.sinkObjectName = sinkObjectName;
    let res = await this.getDicts("transfer_result_object_type");
    this.taskType = res.data.filter((f) =>
      f.dictValue.includes(type)
    )[0].dictLabel;
    res = await getDataTaskconf({
      id: taskId,
    });
    this.databaseInfo = res.data;
    if (sourceDdl && sourceDdl.length > 0) {
      this.ddl = sourceDdl;
      this.executeSqlData = {
        databaseName: this.databaseInfo.sourceName,
        datasourceId: this.databaseInfo.sourceId,
      };
    } else {
      this.ddl = sinkDdl;
      this.executeSqlData = {
        databaseName: this.databaseInfo.sinkName,
        datasourceId: this.databaseInfo.sinkId,
      };
    }
    res = await getAiList();
    Object.keys(this.sort(res)).forEach((f) => {
      this.aiModelList.push({
        label: `${res[f]}(${f})`,
        value: f,
      });
    });
  },
  methods: {
    handleChangeLeftWidth() {
      this.leftWidth = this.leftWidth == "480px" ? "40px" : "480px";
    },
    handleChangeRightWidth() {
      this.rightWidth = this.rightWidth == "480px" ? "40px" : "480px";
    },
    previewMessage(i) {
      this.previewMessageValue = this.historyQuestioning[i];
      this.previewMessageVisible = true;
    },
    sort(data) {
      const sortedData = Object.entries(data).sort((a, b) => {
        const [keyA, valueA] = a;
        const [keyB, valueB] = b;
        return valueA.split("-")[0].localeCompare(valueB.split("-")[0]);
      });
      const result = Object.fromEntries(sortedData);
      return result;
    },
    copyDdl() {
      const dom = document.createElement("input");
      dom.value = this.ddl;
      document.body.appendChild(dom);
      dom.select();
      document.execCommand("copy");
      document.body.removeChild(dom);
      this.$message.success("复制成功");
    },
    editorInit() {
      // 初始化
      require("brace/ext/language_tools");
      require("brace/ext/beautify");
      require("brace/ext/error_marker");
      require("brace/ext/searchbox");
      require("brace/ext/split");
      require("brace/snippets/sql");
      require("brace/mode/sql");
      require("brace/theme/dracula");
    },
    getHistory(history) {
      let arr = [];
      history.forEach((f, i) => {
        // console.log();
        if (i % 2 != 0) {
          if (f.type == "error") {
            return;
          } else {
            arr.unshift({
              title: history[i - 1].message,
              history: {
                user: history[i - 1].message,
                ai: f.message,
              },
            });
          }
        }
      });
      // console.log(arr);
      this.historyQuestioning = arr;
    },
    handleDatabaseInfo(type) {
      getDatasourceInfo({
        id: this.databaseInfo[`${type}Id`],
      }).then((response) => {
        this.databaseInfoValue = response.data;
        this.NextdataDialog = true;
      });
    },
    async testConnect() {
      const {
        type,
        ip,
        port,
        uname,
        pwd,
        databaseName,
        version,
        encoding,
        useUnicode,
        connectTimeout,
        socketTimeout,
        driver,
        url,
      } = this.databaseInfoValue;
      const response = await databaseCheck({
        type,
        ip,
        port,
        uname,
        pwd,
        databaseName,
        version,
        encoding,
        useUnicode,
        connectTimeout,
        socketTimeout,
        driver,
        url,
      });
      if (response.data.code == 200) {
        this.$message({
          message: "连接成功",
          type: "success",
        });
        this.form.testStatus = 0;
      } else {
        this.form.testStatus = 1;
        this.$message.error("连接失败");
      }
      this.getList();
    },
  },
};
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: rgb(245, 247, 250);
  display: flex;
  justify-content: space-between;

  * {
    margin: 0;
    padding: 0;
    font: Inter, -apple-system, BlinkMacSystemFont, Segoe UI, SF Pro SC,
      SF Pro Display, SF Pro Icons, PingFang SC, Hiragino Sans GB,
      Microsoft YaHei, Helvetica Neue, Helvetica, Arial, sans-serif;
    list-style-type: none;
  }

  .boxShadow {
    box-shadow: -10px 0 10px -5px rgba(192, 192, 192, 0.3) !important;
  }

  .chat-left {
    padding: 22px 12px 0px 12px;
    box-sizing: border-box;
    position: relative;
    display: flex;
    flex-direction: column;
    background: #fff;
    height: 100%;
    transition: width 0.2s ease-out;
    box-shadow: 10px 0 10px -5px rgba(192, 192, 192, 0.3);
    .contract {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .contract_title {
        font-size: 20px;
        font-weight: 600;
        position: relative;
        top: 2px;
        white-space: nowrap;
      }

      .svg_box {
        float: right;
        font-size: 17px;
        color: #333333;
        height: 20px;
        cursor: pointer;
      }
    }
    .database_info {
      padding: 5px 0;
      margin: 10px 0;

      li {
        margin: 5px 0;
        font-size: 16px;
        font-weight: 600;

        .database_info-item {
          font-family: "sim";
          font-size: 12px;
          color: #333;
          margin: 5px 0;
          font-weight: 500;
        }
        .database_info-title {
          width: 25%;
          display: inline-block;
        }
      }
    }
  }

  .content {
    width: 100%;
    padding: 15px;
  }
}
</style>

<style scoped>
::v-deep .el-tabs--border-card {
  height: 100%;
}

::v-deep .el-tabs__content,
.el-tab-pane {
  height: 100%;
}
</style>
